package sde.actor.railway;
import sde.actor.*;

public class Controllore extends Actor implements ControlloreIF{
	public static final byte CREATED=0, OPENED=1, CLOSING=2, 
		                              CLOSED=3, OPENING=4;
	private int ct=0; //contatore treni in transito
	private SbarraIF sbarra; //porta di uscita - acquaintance
	public Controllore(){
		become( CREATED );
	}//costruttore
	public void handler( Message m ){
		switch( currentStatus() ){
			case CREATED:
				if( m instanceof Init ){
				     sbarra=((Init)m).sbarra;
				     become( OPENED );
			               } break;
			case OPENED:
				if( m instanceof Arrival ){
				     ct++;
				     sbarra.send( new SbarraIF.ToClose() );
				     become( CLOSING );
				} break;
			case CLOSING:
				if( m instanceof Arrival ){
				     ct++;
				}
				else if( m instanceof Closed ){
				     become( CLOSED );
				} break;
			case CLOSED:
				if( m instanceof Arrival ){
				     ct++;
				}
				else if( m instanceof Departure && ct>1 ){
				     ct--;
				}
				else if( m instanceof Departure && ct==1 ){
				     ct=0;
				     sbarra.send( new SbarraIF.ToOpen() );
				     become( OPENING );
				} break; 
			case OPENING:
				if( m instanceof Arrival ){
				     ct++;
				     sbarra.send( new SbarraIF.ToClose() );
				     become( CLOSING );
				}
				else if( m instanceof Opened ){
				      become( OPENED );
				}
		}//switch
	}//handler
}//Controllore

